// pages/coupon/verify.js
const api = require('../../utils/api');

Page({
  data: {
    storeId: 0,
    storeName: '',
    couponCode: '',
    couponType: ''
  },

  onLoad: function(options) {
    // 获取券类型参数
    if (options.type) {
      this.setData({
        couponType: options.type
      });
    }

    // 获取门店ID，优先级：参数 > 本地存储
    let storeId = 0;
    let storeName = '';
    
    if (options.storeId) {
      storeId = parseInt(options.storeId);
      storeName = options.storeName || '';
    } else {
      storeId = wx.getStorageSync('currentStoreId');
      storeName = wx.getStorageSync('currentStoreName');
    }
    
    if (storeId > 0) {
      this.setData({
        storeId: storeId,
        storeName: storeName
      });
    } else {
      wx.showToast({
        title: '请先选择门店',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 返回上一页
  onTapBack: function() {
    wx.navigateBack({
      fail: function(e) {
        console.log('返回失败', e);
        wx.showToast({
          title: '返回失败',
          icon: 'none'
        });
      }
    });
  },

  // 输入券码
  onInputCode: function(e) {
    this.setData({
      couponCode: e.detail.value
    });
  },

  // 扫码
  onTapScan: function() {
    const that = this;
    wx.scanCode({
      success: function(res) {
        that.setData({
          couponCode: res.result
        });
      },
      fail: function() {
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  // 验证券码
  onVerifyCode: function() {
    const code = this.data.couponCode;
    if (!code) {
      wx.showToast({
        title: '请输入券码',
        icon: 'none'
      });
      return;
    }

    if (this.data.storeId <= 0) {
      wx.showToast({
        title: '门店信息有误',
        icon: 'none'
      });
      return;
    }

    // 显示加载中
    wx.showLoading({
      title: '验证中...'
    });

    // 调用验券API
    api.coupon.verifyCoupon({
      code: code,
      store_id: this.data.storeId,
      type: this.data.couponType
    })
    .then(res => {
      wx.hideLoading();
      
      if (res.success) {
        wx.showToast({
          title: '验证成功',
          icon: 'success'
        });

        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: res.message || '验证失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      wx.hideLoading();
      console.error('验券失败:', err);
      wx.showToast({
        title: '网络错误，请稍后再试',
        icon: 'none'
      });
    });
  }
});